import DexieCtx from "@/utils/dexiectx";

const Proxy = {
  state: () => ({
    proxyList: [],
  }),
  mutations: {
    SET_PROXY_LIST(state, list) {
      // 这里的 `state` 对象是模块的局部状态
      state.proxyList = list
    }
  },
  actions: {
    async addProxyList({ dispatch }, itemList) {
      const dexie = await DexieCtx.db()
      const itemListFormat = itemList.map(item => {
        return { proxy: item }
      })
      console.log(itemListFormat)
      await dexie.proxy.bulkAdd(itemListFormat)
      await dispatch("loadProxyList")
    },
    async deleteProxy({ dispatch }, item) {
      const dexie = await DexieCtx.db()
      await dexie.proxy.where("proxy").equals(item.proxy).delete()
      await dispatch("loadProxyList")
    },
    async updateProxy({ dispatch }, item) {
      const dexie = await DexieCtx.db()
      let newItem = { ...item }
      await dexie.proxy.where("id").equals(item.id).modify(newItem)
      await dispatch("loadProxyList")
    },
    async loadProxyList({ commit }) {
      const dexie = await DexieCtx.db()
      const arr = await dexie.proxy.toArray()
      commit("SET_PROXY_LIST", arr)
      return arr
    },
    async configProxyList({ dispatch, state }) {
      const dexie = await DexieCtx.db()
      const accountsList = await dexie.accounts.toArray()
      const proxyList = state.proxyList
      for (let index = 0; index < accountsList.length; index++) {
        const ac = accountsList[index]
        const proxy = proxyList[index % proxyList.length]
        ac.proxy = proxy.proxy
      }
      const bulkList = accountsList.map(item => {
        return {
          key: item.id,
          changes: item
        }
      })
      await dexie.accounts.bulkUpdate(bulkList)
      dispatch("loadAccounts")
    },
    async resetProxyList({ dispatch, state }) {
      const dexie = await DexieCtx.db()
      const accountsList = await dexie.accounts.toArray()
      for (let index = 0; index < accountsList.length; index++) {
        const ac = accountsList[index]
        ac.proxy = null
      }
      const bulkList = accountsList.map(item => {
        return {
          key: item.id,
          changes: item
        }
      })
      await dexie.accounts.bulkUpdate(bulkList)
      dispatch("loadAccounts")
    }
  },
  getters: {
    proxyList(state) {
      return state.proxyList
    },
  }
}

export default Proxy